package com.yunke.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunke.common.exception.YunkeAssert;
import com.yunke.common.exception.YunkeException;
import com.yunke.common.result.YunkeResultCode;
import com.yunke.common.security.YunkeSecurityUtil;
import com.yunke.common.util.YunkeTimeUtil;
import com.yunke.dto.circle.YunkeCircleCommentDto;
import com.yunke.dto.circle.YunkeCirclePublishDto;
import com.yunke.entity.YunkeCircle;
import com.yunke.entity.YunkeCircleComment;
import com.yunke.entity.YunkeCircleLike;
import com.yunke.entity.YunkeUser;
import com.yunke.mapper.YunkeCircleCommentMapper;
import com.yunke.mapper.YunkeCircleLikeMapper;
import com.yunke.mapper.YunkeCircleMapper;
import com.yunke.mapper.YunkeUserMapper;
import com.yunke.service.YunkeCircleService;
import com.yunke.vo.circle.YunkeCircleCommentVo;
import com.yunke.vo.circle.YunkeCircleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 社交圈Service实现类
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@Service
public class YunkeCircleServiceImpl extends ServiceImpl<YunkeCircleMapper, YunkeCircle> implements YunkeCircleService {

    @Autowired
    private YunkeCircleMapper circleMapper;

    @Autowired
    private YunkeCircleCommentMapper commentMapper;

    @Autowired
    private YunkeCircleLikeMapper likeMapper;

    @Autowired
    private YunkeUserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long publishCircle(YunkeCirclePublishDto publishDto) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("发布动态: userId={}, type={}", userId, publishDto.getType());
        
        // 参数验证
        YunkeAssert.notNull(publishDto.getType(), YunkeResultCode.PARAM_ERROR, "动态类型不能为空");
        YunkeAssert.hasText(publishDto.getContent(), YunkeResultCode.PARAM_ERROR, "动态内容不能为空");
        
        // 根据类型验证必需的媒体文件
        if (publishDto.getType() == 2 || publishDto.getType() == 4) { // 图片或图文
            YunkeAssert.notEmpty(publishDto.getImages(), YunkeResultCode.PARAM_ERROR, "图片类型动态必须包含图片");
        }
        if (publishDto.getType() == 3) { // 视频
            YunkeAssert.hasText(publishDto.getVideo(), YunkeResultCode.PARAM_ERROR, "视频类型动态必须包含视频");
        }
        
        // 创建动态实体
        YunkeCircle circle = new YunkeCircle();
        circle.setUserId(userId);
        circle.setType(publishDto.getType());
        circle.setContent(publishDto.getContent());
        
        // 处理图片
        if (publishDto.getImages() != null && !publishDto.getImages().isEmpty()) {
            circle.setImages(String.join(",", publishDto.getImages()));
        }
        
        // 处理视频
        if (StringUtils.hasText(publishDto.getVideo())) {
            circle.setVideo(publishDto.getVideo());
            circle.setVideoCover(publishDto.getVideoCover());
        }
        
        // 处理位置信息
        if (StringUtils.hasText(publishDto.getLocation())) {
            circle.setLocation(publishDto.getLocation());
            circle.setLongitude(publishDto.getLongitude());
            circle.setLatitude(publishDto.getLatitude());
        }
        
        // 设置其他属性
        circle.setAllowComment(publishDto.getAllowComment());
        circle.setVisibility(publishDto.getVisibility());
        circle.setLikeCount(0);
        circle.setCommentCount(0);
        circle.setShareCount(0);
        circle.setViewCount(0);
        circle.setIsTop(0);
        circle.setIsHot(0);
        circle.setStatus(1); // 正常状态
        
        // 保存到数据库
        save(circle);
        
        log.info("发布动态成功: userId={}, circleId={}", userId, circle.getId());
        return circle.getId();
    }

    @Override
    public Page<YunkeCircleVo> getCircleList(Long current, Long size, Integer type, String location) {
        log.info("获取动态列表: current={}, size={}, type={}, location={}", current, size, type, location);
        
        // 构建查询条件
        LambdaQueryWrapper<YunkeCircle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YunkeCircle::getStatus, 1); // 只查询正常状态的动态
        wrapper.eq(YunkeCircle::getVisibility, 1); // 只查询公开可见的动态
        
        if (type != null) {
            wrapper.eq(YunkeCircle::getType, type);
        }
        
        if (StringUtils.hasText(location)) {
            wrapper.like(YunkeCircle::getLocation, location);
        }
        
        // 排序：置顶 > 热门 > 时间倒序
        wrapper.orderByDesc(YunkeCircle::getIsTop)
               .orderByDesc(YunkeCircle::getIsHot)
               .orderByDesc(YunkeCircle::getCreateTime);
        
        // 分页查询
        Page<YunkeCircle> page = new Page<>(current, size);
        Page<YunkeCircle> circlePages = page(page, wrapper);
        
        // 转换为VO
        Page<YunkeCircleVo> result = new Page<>(current, size);
        result.setTotal(circlePages.getTotal());
        result.setPages(circlePages.getPages());
        
        List<YunkeCircleVo> circleVos = circlePages.getRecords().stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
        
        result.setRecords(circleVos);
        
        log.info("获取动态列表成功: total={}", result.getTotal());
        return result;
    }

    @Override
    public YunkeCircleVo getCircleDetail(Long circleId) {
        log.info("获取动态详情: circleId={}", circleId);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        
        // 查询动态
        YunkeCircle circle = getById(circleId);
        YunkeAssert.notNull(circle, YunkeResultCode.NOT_FOUND, "动态不存在");
        YunkeAssert.isTrue(circle.getStatus() == 1, YunkeResultCode.NOT_FOUND, "动态已被删除");
        
        // 增加浏览数
        circle.setViewCount(circle.getViewCount() + 1);
        updateById(circle);
        
        // 转换为VO
        YunkeCircleVo circleVo = convertToVo(circle);
        
        log.info("获取动态详情成功: circleId={}", circleId);
        return circleVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean likeCircle(Long circleId) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("点赞/取消点赞动态: userId={}, circleId={}", userId, circleId);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        
        // 查询动态
        YunkeCircle circle = getById(circleId);
        YunkeAssert.notNull(circle, YunkeResultCode.NOT_FOUND, "动态不存在");
        YunkeAssert.isTrue(circle.getStatus() == 1, YunkeResultCode.NOT_FOUND, "动态已被删除");
        
        // 查询是否已点赞
        YunkeCircleLike existLike = likeMapper.selectOne(
            new LambdaQueryWrapper<YunkeCircleLike>()
                .eq(YunkeCircleLike::getUserId, userId)
                .eq(YunkeCircleLike::getTargetId, circleId)
                .eq(YunkeCircleLike::getType, 1) // 动态点赞
        );
        
        boolean isLiked = false;
        if (existLike == null) {
            // 新增点赞
            YunkeCircleLike like = new YunkeCircleLike();
            like.setUserId(userId);
            like.setTargetId(circleId);
            like.setType(1); // 动态点赞
            like.setCreateTime(YunkeTimeUtil.timestampToLocalDateTime(System.currentTimeMillis()));
            like.setUpdateTime(YunkeTimeUtil.timestampToLocalDateTime(System.currentTimeMillis()));
            like.setStatus(1); // 已点赞
            like.setIpAddress(getClientIp());
            likeMapper.insert(like);
            
            // 增加点赞数
            circle.setLikeCount(circle.getLikeCount() + 1);
            isLiked = true;
        } else {
            if (existLike.getStatus() == 1) {
                // 取消点赞
                existLike.setStatus(0);
                likeMapper.updateById(existLike);
                
                // 减少点赞数
                circle.setLikeCount(Math.max(0, circle.getLikeCount() - 1));
                isLiked = false;
            } else {
                // 重新点赞
                existLike.setStatus(1);
                likeMapper.updateById(existLike);
                
                // 增加点赞数
                circle.setLikeCount(circle.getLikeCount() + 1);
                isLiked = true;
            }
        }
        
        updateById(circle);
        
        log.info("点赞/取消点赞动态成功: userId={}, circleId={}, isLiked={}", userId, circleId, isLiked);
        return isLiked;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addComment(YunkeCircleCommentDto commentDto) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("发表评论: userId={}, circleId={}", userId, commentDto.getCircleId());
        
        // 参数验证
        YunkeAssert.notNull(commentDto.getCircleId(), YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        YunkeAssert.hasText(commentDto.getContent(), YunkeResultCode.PARAM_ERROR, "评论内容不能为空");
        
        // 查询动态
        YunkeCircle circle = getById(commentDto.getCircleId());
        YunkeAssert.notNull(circle, YunkeResultCode.NOT_FOUND, "动态不存在");
        YunkeAssert.isTrue(circle.getStatus() == 1, YunkeResultCode.NOT_FOUND, "动态已被删除");
        YunkeAssert.isTrue(circle.getAllowComment() == 1, YunkeResultCode.FORBIDDEN, "该动态不允许评论");
        
        // 如果是回复评论，验证父评论
        if (commentDto.getParentId() != null && commentDto.getParentId() > 0) {
            YunkeCircleComment parentComment = commentMapper.selectById(commentDto.getParentId());
            YunkeAssert.notNull(parentComment, YunkeResultCode.NOT_FOUND, "被回复的评论不存在");
            YunkeAssert.isTrue(parentComment.getStatus() == 1, YunkeResultCode.NOT_FOUND, "被回复的评论已被删除");
        }
        
        // 创建评论
        YunkeCircleComment comment = new YunkeCircleComment();
        comment.setCircleId(commentDto.getCircleId());
        comment.setUserId(userId);
        comment.setParentId(commentDto.getParentId());
        comment.setReplyUserId(commentDto.getReplyUserId());
        comment.setContent(commentDto.getContent());
        
        // 处理图片
        if (commentDto.getImages() != null && !commentDto.getImages().isEmpty()) {
            comment.setImages(String.join(",", commentDto.getImages()));
        }
        
        comment.setLikeCount(0);
        comment.setReplyCount(0);
        comment.setStatus(1);
        comment.setIpAddress(getClientIp());
        comment.setLocation(""); // 可根据IP获取位置
        
        commentMapper.insert(comment);
        
        // 更新动态评论数
        circle.setCommentCount(circle.getCommentCount() + 1);
        updateById(circle);
        
        // 如果是回复评论，更新父评论的回复数
        if (comment.getParentId() != null && comment.getParentId() > 0) {
            YunkeCircleComment parentComment = commentMapper.selectById(comment.getParentId());
            if (parentComment != null) {
                parentComment.setReplyCount(parentComment.getReplyCount() + 1);
                commentMapper.updateById(parentComment);
            }
        }
        
        log.info("发表评论成功: userId={}, circleId={}, commentId={}", userId, commentDto.getCircleId(), comment.getId());
        return comment.getId();
    }

    @Override
    public Page<YunkeCircleCommentVo> getCommentList(Long circleId, Long current, Long size) {
        log.info("获取评论列表: circleId={}, current={}, size={}", circleId, current, size);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        
        // 查询顶级评论
        LambdaQueryWrapper<YunkeCircleComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YunkeCircleComment::getCircleId, circleId)
               .eq(YunkeCircleComment::getStatus, 1)
               .isNull(YunkeCircleComment::getParentId)
               .orderByDesc(YunkeCircleComment::getCreateTime);
        
        Page<YunkeCircleComment> page = new Page<>(current, size);
        Page<YunkeCircleComment> commentPages = commentMapper.selectPage(page, wrapper);
        
        // 转换为VO
        Page<YunkeCircleCommentVo> result = new Page<>(current, size);
        result.setTotal(commentPages.getTotal());
        result.setPages(commentPages.getPages());
        
        List<YunkeCircleCommentVo> commentVos = commentPages.getRecords().stream()
                .map(this::convertCommentToVo)
                .collect(Collectors.toList());
        
        result.setRecords(commentVos);
        
        log.info("获取评论列表成功: circleId={}, total={}", circleId, result.getTotal());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean likeComment(Long commentId) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("点赞/取消点赞评论: userId={}, commentId={}", userId, commentId);
        
        // 参数验证
        YunkeAssert.notNull(commentId, YunkeResultCode.PARAM_ERROR, "评论ID不能为空");
        
        // 查询评论
        YunkeCircleComment comment = commentMapper.selectById(commentId);
        YunkeAssert.notNull(comment, YunkeResultCode.NOT_FOUND, "评论不存在");
        YunkeAssert.isTrue(comment.getStatus() == 1, YunkeResultCode.NOT_FOUND, "评论已被删除");
        
        // 查询是否已点赞
        YunkeCircleLike existLike = likeMapper.selectOne(
            new LambdaQueryWrapper<YunkeCircleLike>()
                .eq(YunkeCircleLike::getUserId, userId)
                .eq(YunkeCircleLike::getTargetId, commentId)
                .eq(YunkeCircleLike::getType, 2) // 评论点赞
        );
        
        boolean isLiked = false;
        if (existLike == null) {
            // 新增点赞
            YunkeCircleLike like = new YunkeCircleLike();
            like.setUserId(userId);
            like.setTargetId(commentId);
            like.setType(2); // 评论点赞
            like.setCreateTime(YunkeTimeUtil.timestampToLocalDateTime(System.currentTimeMillis()));
            like.setUpdateTime(YunkeTimeUtil.timestampToLocalDateTime(System.currentTimeMillis()));
            like.setStatus(1); // 已点赞
            like.setIpAddress(getClientIp());
            likeMapper.insert(like);
            
            // 增加点赞数
            comment.setLikeCount(comment.getLikeCount() + 1);
            isLiked = true;
        } else {
            if (existLike.getStatus() == 1) {
                // 取消点赞
                existLike.setStatus(0);
                likeMapper.updateById(existLike);
                
                // 减少点赞数
                comment.setLikeCount(Math.max(0, comment.getLikeCount() - 1));
                isLiked = false;
            } else {
                // 重新点赞
                existLike.setStatus(1);
                likeMapper.updateById(existLike);
                
                // 增加点赞数
                comment.setLikeCount(comment.getLikeCount() + 1);
                isLiked = true;
            }
        }
        
        commentMapper.updateById(comment);
        
        log.info("点赞/取消点赞评论成功: userId={}, commentId={}, isLiked={}", userId, commentId, isLiked);
        return isLiked;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCircle(Long circleId) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("删除动态: userId={}, circleId={}", userId, circleId);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        
        // 查询动态
        YunkeCircle circle = getById(circleId);
        YunkeAssert.notNull(circle, YunkeResultCode.NOT_FOUND, "动态不存在");
        YunkeAssert.isTrue(circle.getStatus() == 1, YunkeResultCode.NOT_FOUND, "动态已被删除");
        
        // 检查权限：只能删除自己的动态
        YunkeAssert.isTrue(circle.getUserId().equals(userId), YunkeResultCode.FORBIDDEN, "只能删除自己的动态");
        
        // 软删除动态
        circle.setStatus(0);
        boolean result = updateById(circle);
        
        if (result) {
            // 删除相关的评论和点赞记录
            // 软删除所有评论
            commentMapper.update(null,
                new LambdaUpdateWrapper<YunkeCircleComment>()
                    .eq(YunkeCircleComment::getCircleId, circleId)
                    .set(YunkeCircleComment::getStatus, 0)
            );
            
            // 删除点赞记录
            likeMapper.delete(
                new LambdaQueryWrapper<YunkeCircleLike>()
                    .eq(YunkeCircleLike::getTargetId, circleId)
                    .eq(YunkeCircleLike::getType, 1)
            );
        }
        
        log.info("删除动态成功: userId={}, circleId={}", userId, circleId);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("删除评论: userId={}, commentId={}", userId, commentId);
        
        // 参数验证
        YunkeAssert.notNull(commentId, YunkeResultCode.PARAM_ERROR, "评论ID不能为空");
        
        // 查询评论
        YunkeCircleComment comment = commentMapper.selectById(commentId);
        YunkeAssert.notNull(comment, YunkeResultCode.NOT_FOUND, "评论不存在");
        YunkeAssert.isTrue(comment.getStatus() == 1, YunkeResultCode.NOT_FOUND, "评论已被删除");
        
        // 检查权限：只能删除自己的评论或自己动态下的评论
        YunkeCircle circle = getById(comment.getCircleId());
        YunkeAssert.isTrue(comment.getUserId().equals(userId) || 
                          (circle != null && circle.getUserId().equals(userId)), 
                          YunkeResultCode.FORBIDDEN, "只能删除自己的评论或自己动态下的评论");
        
        // 软删除评论
        comment.setStatus(0);
        int result = commentMapper.updateById(comment);
        
        if (result > 0) {
            // 更新动态评论数
            if (circle != null) {
                circle.setCommentCount(Math.max(0, circle.getCommentCount() - 1));
                updateById(circle);
            }
            
            // 如果是子评论，更新父评论的回复数
            if (comment.getParentId() != null && comment.getParentId() > 0) {
                YunkeCircleComment parentComment = commentMapper.selectById(comment.getParentId());
                if (parentComment != null) {
                    parentComment.setReplyCount(Math.max(0, parentComment.getReplyCount() - 1));
                    commentMapper.updateById(parentComment);
                }
            }
            
            // 删除评论的点赞记录
            likeMapper.delete(
                new LambdaQueryWrapper<YunkeCircleLike>()
                    .eq(YunkeCircleLike::getTargetId, commentId)
                    .eq(YunkeCircleLike::getType, 2)
            );
        }
        
        log.info("删除评论成功: userId={}, commentId={}", userId, commentId);
        return result > 0;
    }

    @Override
    public Page<YunkeCircleVo> getMyCircleList(Long current, Long size) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("获取我的动态列表: userId={}, current={}, size={}", userId, current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<YunkeCircle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YunkeCircle::getUserId, userId)
               .eq(YunkeCircle::getStatus, 1)
               .orderByDesc(YunkeCircle::getCreateTime);
        
        // 分页查询
        Page<YunkeCircle> page = new Page<>(current, size);
        Page<YunkeCircle> circlePages = page(page, wrapper);
        
        // 转换为VO
        Page<YunkeCircleVo> result = new Page<>(current, size);
        result.setTotal(circlePages.getTotal());
        result.setPages(circlePages.getPages());
        
        List<YunkeCircleVo> circleVos = circlePages.getRecords().stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
        
        result.setRecords(circleVos);
        
        log.info("获取我的动态列表成功: userId={}, total={}", userId, result.getTotal());
        return result;
    }

    @Override
    public Page<YunkeCircleVo> getFollowCircleList(Long current, Long size) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("获取关注用户动态列表: userId={}, current={}, size={}", userId, current, size);
        
        // TODO: 这里需要根据关注关系查询，暂时返回空列表
        // 实际实现需要联查用户关注表
        Page<YunkeCircleVo> result = new Page<>(current, size);
        result.setTotal(0L);
        result.setPages(0L);
        result.setRecords(new ArrayList<>());
        
        log.info("获取关注用户动态列表成功: userId={}, total={}", userId, result.getTotal());
        return result;
    }

    @Override
    public boolean reportCircle(Long circleId, String reason) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("举报动态: userId={}, circleId={}, reason={}", userId, circleId, reason);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        YunkeAssert.hasText(reason, YunkeResultCode.PARAM_ERROR, "举报原因不能为空");
        
        // 查询动态
        YunkeCircle circle = getById(circleId);
        YunkeAssert.notNull(circle, YunkeResultCode.NOT_FOUND, "动态不存在");
        YunkeAssert.isTrue(circle.getStatus() == 1, YunkeResultCode.NOT_FOUND, "动态已被删除");
        
        // TODO: 实现举报逻辑，可以创建举报记录表
        // 这里简单记录日志
        log.warn("用户举报动态: userId={}, circleId={}, reason={}", userId, circleId, reason);
        
        return true;
    }

    @Override
    public boolean blockCircle(Long circleId) {
        // 检查登录状态
        YunkeSecurityUtil.checkLogin();
        
        Long userId = YunkeSecurityUtil.getCurrentUserId();
        log.info("屏蔽动态: userId={}, circleId={}", userId, circleId);
        
        // 参数验证
        YunkeAssert.notNull(circleId, YunkeResultCode.PARAM_ERROR, "动态ID不能为空");
        
        // TODO: 实现屏蔽逻辑，可以创建用户屏蔽记录表
        // 这里简单记录日志
        log.info("用户屏蔽动态: userId={}, circleId={}", userId, circleId);
        
        return true;
    }

    /**
     * 转换动态实体为VO
     */
    private YunkeCircleVo convertToVo(YunkeCircle circle) {
        YunkeCircleVo vo = new YunkeCircleVo();
        vo.setId(circle.getId());
        vo.setType(circle.getType());
        vo.setContent(circle.getContent());
        vo.setLocation(circle.getLocation());
        vo.setLikeCount(circle.getLikeCount());
        vo.setCommentCount(circle.getCommentCount());
        vo.setShareCount(circle.getShareCount());
        vo.setViewCount(circle.getViewCount());
        vo.setIsTop(circle.getIsTop() == 1);
        vo.setIsHot(circle.getIsHot() == 1);
        vo.setCreateTime(YunkeTimeUtil.localDateTimeToTimestamp(circle.getCreateTime()));
        vo.setCreateTimeText(formatTime(YunkeTimeUtil.localDateTimeToTimestamp(circle.getCreateTime())));
        
        // 处理图片列表
        if (StringUtils.hasText(circle.getImages())) {
            vo.setImages(List.of(circle.getImages().split(",")));
        }
        
        // 处理视频
        vo.setVideo(circle.getVideo());
        vo.setVideoCover(circle.getVideoCover());
        
        // 查询用户信息
        YunkeUser user = userMapper.selectById(circle.getUserId());
        if (user != null) {
            YunkeCircleVo.UserInfo userInfo = new YunkeCircleVo.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setNickname(user.getNickname());
            userInfo.setAvatar(user.getAvatar());
            userInfo.setVipLevel(user.getVipLevel());
            userInfo.setIsAuth(user.getIsAuthentication() == 1);
            vo.setUser(userInfo);
        }
        
        // 检查当前用户是否已点赞
        if (YunkeSecurityUtil.isLogin()) {
            Long currentUserId = YunkeSecurityUtil.getCurrentUserId();
            YunkeCircleLike like = likeMapper.selectOne(
                new LambdaQueryWrapper<YunkeCircleLike>()
                    .eq(YunkeCircleLike::getUserId, currentUserId)
                    .eq(YunkeCircleLike::getTargetId, circle.getId())
                    .eq(YunkeCircleLike::getType, 1)
                    .eq(YunkeCircleLike::getStatus, 1)
            );
            vo.setIsLiked(like != null);
        } else {
            vo.setIsLiked(false);
        }
        
        // 获取最新评论（前3条）
        List<YunkeCircleComment> latestComments = commentMapper.selectList(
            new LambdaQueryWrapper<YunkeCircleComment>()
                .eq(YunkeCircleComment::getCircleId, circle.getId())
                .eq(YunkeCircleComment::getStatus, 1)
                .isNull(YunkeCircleComment::getParentId)
                .orderByDesc(YunkeCircleComment::getCreateTime)
                .last("LIMIT 3")
        );
        
        List<YunkeCircleCommentVo> commentVos = latestComments.stream()
                .map(this::convertCommentToVo)
                .collect(Collectors.toList());
        vo.setLatestComments(commentVos);
        
        return vo;
    }

    /**
     * 转换评论实体为VO
     */
    private YunkeCircleCommentVo convertCommentToVo(YunkeCircleComment comment) {
        YunkeCircleCommentVo vo = new YunkeCircleCommentVo();
        vo.setId(comment.getId());
        vo.setCircleId(comment.getCircleId());
        vo.setParentId(comment.getParentId());
        vo.setContent(comment.getContent());
        vo.setLikeCount(comment.getLikeCount());
        vo.setReplyCount(comment.getReplyCount());
        vo.setCreateTime(YunkeTimeUtil.localDateTimeToTimestamp(comment.getCreateTime()));
        vo.setCreateTimeText(formatTime(YunkeTimeUtil.localDateTimeToTimestamp(comment.getCreateTime())));
        vo.setLocation(comment.getLocation());
        
        // 处理图片列表
        if (StringUtils.hasText(comment.getImages())) {
            vo.setImages(List.of(comment.getImages().split(",")));
        }
        
        // 查询评论用户信息
        YunkeUser user = userMapper.selectById(comment.getUserId());
        if (user != null) {
            YunkeCircleCommentVo.UserInfo userInfo = new YunkeCircleCommentVo.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setNickname(user.getNickname());
            userInfo.setAvatar(user.getAvatar());
            userInfo.setVipLevel(user.getVipLevel());
            userInfo.setIsAuth(user.getIsAuthentication() == 1);
            vo.setUser(userInfo);
        }
        
        // 查询被回复用户信息
        if (comment.getReplyUserId() != null) {
            YunkeUser replyUser = userMapper.selectById(comment.getReplyUserId());
            if (replyUser != null) {
                YunkeCircleCommentVo.UserInfo replyUserInfo = new YunkeCircleCommentVo.UserInfo();
                replyUserInfo.setUserId(replyUser.getId());
                replyUserInfo.setNickname(replyUser.getNickname());
                replyUserInfo.setAvatar(replyUser.getAvatar());
                replyUserInfo.setVipLevel(replyUser.getVipLevel());
                replyUserInfo.setIsAuth(replyUser.getIsAuthentication() == 1);
                vo.setReplyUser(replyUserInfo);
            }
        }
        
        // 检查当前用户是否已点赞
        if (YunkeSecurityUtil.isLogin()) {
            Long currentUserId = YunkeSecurityUtil.getCurrentUserId();
            YunkeCircleLike like = likeMapper.selectOne(
                new LambdaQueryWrapper<YunkeCircleLike>()
                    .eq(YunkeCircleLike::getUserId, currentUserId)
                    .eq(YunkeCircleLike::getTargetId, comment.getId())
                    .eq(YunkeCircleLike::getType, 2)
                    .eq(YunkeCircleLike::getStatus, 1)
            );
            vo.setIsLiked(like != null);
        } else {
            vo.setIsLiked(false);
        }
        
        return vo;
    }

    /**
     * 格式化时间
     */
    private String formatTime(Long timestamp) {
        if (timestamp == null) {
            return "";
        }
        
        long now = System.currentTimeMillis();
        long diff = now - timestamp;
        
        if (diff < 60 * 1000) {
            return "刚刚";
        } else if (diff < 60 * 60 * 1000) {
            return (diff / (60 * 1000)) + "分钟前";
        } else if (diff < 24 * 60 * 60 * 1000) {
            return (diff / (60 * 60 * 1000)) + "小时前";
        } else if (diff < 7 * 24 * 60 * 60 * 1000) {
            return (diff / (24 * 60 * 60 * 1000)) + "天前";
        } else {
            LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, 
                    java.time.ZoneOffset.ofHours(8));
            return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp() {
        // TODO: 实现获取客户端IP的逻辑
        return "127.0.0.1";
    }
} 